package com.websocket;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.servlet.Getpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class SystemTimer {
	@Autowired
	Getpoint getpoint;
	static SystemTimer systemTimer = null;
	private SystemTimer(){
		/***********单独开启一个定时任务，定时没分钟给所有接入着发送一个消息提示**************/
		//获取当前时间，如果当前时间的秒不�?，则分钟�?��+1
		Calendar calendar = Calendar.getInstance();
		Date currentTime = calendar.getTime();
		final Date newTime = this.getNewTime(currentTime);
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				try {
					String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEE").format(new Date());
					String value=
							new ObjectMapper().writeValueAsString(getpoint.getPointsjiaozhun());
					getpoint.setPointsjiaozhun(new ArrayList<>());
				System.out.println("我在定时器里?" + WebSocketMessage.getSessionSet());
				for (Session session : WebSocketMessage.getSessionSet()) {
						session.getBasicRemote().sendText("时间："+currentTime+"\n数据："+value);
				}
				} catch (Exception e) {
				e.printStackTrace();
			}
			}
		}, newTime,1000*5);
		/*************************/
	}
	public static SystemTimer getInstance(){
		if(systemTimer == null){
			synchronized (SystemTimer.class) {
				if(systemTimer == null){
					systemTimer = new SystemTimer();
				}
			}
		}
		return systemTimer;
	}
	
	/**
	 * <pre>
	 * 根据当前时间，返回下�?��钟，整分钟的时间
	 * </pre>
	 */
	private Date getNewTime(Date currentTime){
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.SECOND, 0);
		int minute = calendar.get(Calendar.MINUTE);
		calendar.set(Calendar.MINUTE, minute + 1);
		return calendar.getTime();
	}

}
